import { message } from 'antd';
import store, {setDevice} from '@/store'
import NiceModal from '@ebay/nice-modal-react';


// 更新设备列表
export const syncDevices = async () => {
    const devices = await electronAPI.loadDevices();
    console.log(111, devices);
    

    let deviceId;
    // 如果只有一台，直接更新到全局，否则弹窗让用户选择
    if(devices.length===1){
        deviceId = devices[0].id
    }else if(devices.length>1){
        deviceId = await NiceModal.show('select-device', { devices })
    }
    store.dispatch(setDevice(deviceId));
   
}

// 监听usb改变的回调
const onUsbChange = (value) => {
    const msg = value.status === 'attach' ? '检测到有设备插入' : '检测到有设备拔出'
    message.info(msg);
    setTimeout(() => { // 设备插入后立即调用adb devices会查不到，延迟0.5s即可
        syncDevices()
    }, 1000)
}

// 项目初始化就执行
if(window.electronAPI){
    syncDevices();
    electronAPI.onUsbChange(onUsbChange)
}